#include <cstdlib>
#include <iostream>
#include <alibabacloud/core/AlibabaCloud.h>
#include <alibabacloud/core/CommonRequest.h>
#include <alibabacloud/core/CommonClient.h>
#include <alibabacloud/core/CommonResponse.h>
#include <memory>
#include "Logger.hpp"
using namespace std;
using namespace AlibabaCloud;

namespace chatroom{
    class DMSClient{
    public:
        using Ptr = std::shared_ptr<DMSClient>;
        DMSClient(const std::string& key_id,const std::string& key_secret){
            AlibabaCloud::InitializeSdk();
            AlibabaCloud::ClientConfiguration configuration( "cn-qingdao" );
            // specify timeout when create client.
            configuration.setConnectTimeout(1500);
            configuration.setReadTimeout(4000);
            AlibabaCloud::Credentials credential(key_id, key_secret);
            _client = std::make_unique<AlibabaCloud::CommonClient>(credential, configuration);
        }
        bool Send(const std::string& phone,const std::string& code)
        {
            AlibabaCloud::CommonRequest request(AlibabaCloud::CommonRequest::RequestPattern::RpcPattern);
            request.setHttpMethod(AlibabaCloud::HttpRequest::Method::Post);
            request.setDomain("dysmsapi.aliyuncs.com");
            request.setVersion("2017-05-25");
            request.setQueryParameter("Action", "SendSms");
            request.setQueryParameter("SignName", "阿里云通信");
            request.setQueryParameter("TemplateCode", "SMS_319045258");
            request.setQueryParameter("PhoneNumbers", phone);
            std::string str = "{\"code\":\""+str+"\"}";
            request.setQueryParameter("TemplateParam", str);

            auto response = _client->commonResponse(request);
            if (!response.isSuccess())
            {
                Logger_ERROR("短信验证码发送失败{}",response.error().errorMessage());
                return false;
            }
            // AlibabaCloud::ShutdownSdk();
            return true;
        }
    private:
        std::unique_ptr<AlibabaCloud::CommonClient> _client;
    };
}